package com.example.api.mall.aspect;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 访问日志切面
 * @author xw.s
 * @date 2021/4/7
 */
@Aspect
@Component
@Slf4j
public class LogAspect {

    //基于方法
    @Pointcut("execution(* com.example..*..controller..*.*(..))")
    public void pointCut(){}

    //基于注解
//    @Pointcut("@annotation(com.example.api.mall.annotation.AccessLimit)")
//    public void pointCutAccessLimit(){}

    //前置通知
    @Before("pointCut()")
    public void before(JoinPoint joinPoint) throws IOException {
        log.info("开始前置通知");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();//获取请求
        HttpServletRequest request = attributes.getRequest();
        log.info("请求类型：" + request.getMethod());
        log.info("请求URI：" + request.getRequestURI());
        log.info("请求URL：" + request.getRequestURL());
        log.info("请求IP：" + request.getRemoteAddr());
        Signature signature = joinPoint.getSignature();// 获取签名
        log.info("请求包名：" + signature.getDeclaringTypeName());
        log.info("请求方法: " + signature.getName());
        log.info("请求参数：" + JSONUtil.toJsonStr(joinPoint.getArgs()));//TODO 要屏蔽，小心记录密码
        log.info("结束前置通知");
    }

    /**
     * 环绕通知
     * @return
     */
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        log.info("开始环绕通知");
        long startTime = System.currentTimeMillis();
        Object result = point.proceed();
        log.info("请求结果：" + JSONUtil.toJsonStr(result));
        log.info("请求耗时：{} ms", System.currentTimeMillis() - startTime);
        log.info("结束环绕通知");
        return result;
    }

    /**
     * 后置通知
     * @return
     */
    @After("pointCut()")
    public void after(JoinPoint point) throws Throwable {
        log.info("开始后置通知");
        log.info("结束后置通知");
    }

    /**
     * 切点返回内容后，一般用于对返回值进行加工
     */
    @AfterReturning("pointCut()")
    public void afterReturning(JoinPoint point){
        log.info("开始afterReturning通知");
        log.info("结束afterReturning通知");
    }

    /**
     * 抛出异常后处理
     */
    @AfterThrowing("pointCut()")
    public void afterThrowing(JoinPoint point){
        log.info("开始afterThrowing通知");
        log.info("结束afterThrowing通知");
    }
}
